package technical.gps;

import javax.microedition.location.Coordinates;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;

/* gpsReq.java
 * 
 * Alfred Olschnoegger
 * 19.05.2008
 */

/**
 * TODO description
 * 
 * @date 19.05.2008
 * @author Alfred Olschnoegger
 */

public class  gpsReader extends Thread {

	private static final int s_Timeout = 20;
	private static final int s_MaxAge = 4;

	private float m_Altitude = 0;
	private double m_Latitude = 0;
	private double m_Longitude = 0;

	private boolean m_Available = false;
	private boolean m_Updating = true;

	private gpsReader_Observer m_Observer;

	public gpsReader(gpsReader_Observer observer) {
		m_Observer = observer;
		getData();
	}


	public void run() {
		while(m_Updating) {
			getData();
			try {
				sleep(1000 * s_MaxAge);
				m_Observer.updateLocation();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	private void getData() {
		// setting up the criterias
		Criteria crit1 = new Criteria();
		//crit1.setHorizontalAccuracy(500); // 1m
		//crit1.setVerticalAccuracy(1); // 1m
		// crit1.setPreferredResponseTime(Criteria.NO_REQUIREMENT);
		// crit1.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);
		// crit1.setCostAllowed(false);
		// crit1.setSpeedAndCourseRequired(true);
		// crit1.setAltitudeRequired(true);
		// crit1.setAddressInfoRequired(true);
		LocationProvider provider = null;

		
		while (provider == null) {
			try {
				
				provider = LocationProvider.getInstance(crit1);
				// reading current position
				Location l = provider.getLocation(s_Timeout);
				Coordinates c = l.getQualifiedCoordinates();
				if (c != null) {
					m_Latitude = c.getLatitude();
					m_Longitude = c.getLongitude();
					m_Altitude = c.getAltitude();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public float getAltitude() {
		return m_Altitude;
	}
	
	public double getLatitude() {
		return m_Latitude;
	}

	public double getLongitude() {
		return m_Longitude;
	}

//	public double getLatitude() {
//		return 47.40670177;
//	}
//
//	public double getLongitude() {
//		return 9.743500031;
//	}

	

	public boolean isAvailable() {
		return m_Available;
	}

	public void setUpdating(boolean updating) {
		m_Updating = updating;
		if(m_Updating==true) 
			m_Observer.updateLocation();
	}
}

// end of gpsReq.java
